package com.chy.blog_server.core.util;

import cn.hutool.json.JSONUtil;
import com.chy.blog_server.modular.system.entity.SysUser;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.Map;

/**
 * 描述：分页参数和搜索条件参数工具类
 * 作者：chenhuiyan
 * 时间：2020/902/22 21:40
 */
public class PageAndParamUtil {

    private static Integer limit = 15; //每页条数

    private static Integer page = 1; //页数

    private static Integer size = limit * page; //偏移量

    private static Map<String, Object> params = new HashMap<>(); //存放搜索条件参数和分页参数


    /**
     * 获取一个request对象的方法
     *
     * @return HttpServletRequest
     */
    public static HttpServletRequest getRequest() {
        ServletRequestAttributes attrs = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        return (HttpServletRequest) attrs.getRequest();
    }

    public static Map<String, Object> getParams(){

        HttpServletRequest request = getRequest();

        //json格式搜索条件参数处理
        params = JSONUtil.parseObj(request.getParameter("searchParams"));

        //键值对格式搜索条件参数处理
        Map<String, String[]> pa = new HashMap<>();
        pa = request.getParameterMap();
        String[] arr = null;
        for(Map.Entry<String, String[]> map: pa.entrySet()){
            if(!"searchParams".equals(map.getKey())){
                arr = map.getValue();
                params.put(map.getKey(), arr[0]);
            }
        }

        limit = 15;
        if(StringUtil.notNull(params.get("limit") + "")){
            limit = Integer.valueOf(params.get("limit") + "");
        }
        page = 1;
        if(StringUtil.notNull(params.get("page") + "")){
            page = Integer.valueOf(params.get("page") + "");
        }
        size = limit * (page - 1);

        params.put("limit", limit);
        params.put("page", page);
        params.put("size", size);

        return params;
    }

}
